package com.boniu.startapp;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.util.List;

public class AccessibilityUtils {
    //是否开启权限
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean isQuanxOpen(Context context){
        String manufacturer = Build.MANUFACTURER;
        if (manufacturer != null && manufacturer.length()>0){
            String phone_type = manufacturer.toLowerCase();
            if ("vivo".equals(phone_type)){
                if (isServiceON(context) && getFloatPermissionStatus(context) == 0){
                    return true;
                }
            }else{
                if (isServiceON(context) && Settings.canDrawOverlays(context)) {
                    return true;
                }
            }
        }
        return false;
    }
    //无障碍权限
    public static boolean isServiceON(Context context){
        ActivityManager activityManager = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo>
                runningServices = activityManager.getRunningServices(100);
        if (runningServices.size() < 0 ){
            return false;
        }
        for (int i = 0;i<runningServices.size();i++){
            ComponentName service = runningServices.get(i).service;
            if (service.getClassName().contains(context.getPackageName())){
                return true;
            }
        }
        return false;
    }




    //是否有后台运行权限
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean isIgnoringBatteryOptimizations(Context context) {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
        return isIgnoring;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void requestXfcWindow(Context context){
        String manufacturer = Build.MANUFACTURER;
        if (manufacturer != null && manufacturer.length()>0){
            String phone_type = manufacturer.toLowerCase();
            if ("vivo".equals(phone_type)){
                try {
                    Intent localIntent;
                    if (((Build.MODEL.contains("Y85")) && (!Build.MODEL.contains("Y85A"))) || (Build.MODEL.contains("vivo Y53L"))) {
                        localIntent = new Intent();
                        localIntent.setClassName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.PurviewTabActivity");
                        localIntent.putExtra("packagename", context.getPackageName());
                        localIntent.putExtra("tabId", "1");
                        context.startActivity(localIntent);
                    } else {
                        localIntent = new Intent();
                        localIntent.setClassName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity");
                        localIntent.setAction("secure.intent.action.softPermissionDetail");
                        localIntent.putExtra("packagename", context.getPackageName());
                        context.startActivity(localIntent);
                    }
                }catch (Exception e){
                    Log.e("asd", "requestXfcWindow: " + e.getLocalizedMessage() );
                }

            }else{
                requestXfc(context);
            }
        }
    }


    //申请悬浮窗权限
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void requestXfc(Context context){
        if (!Settings.canDrawOverlays(context)) {
            Intent intent_dol = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
            intent_dol.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent_dol, PackageManager.MATCH_ALL);
            if (resolveInfo != null) {
                context.startActivity(intent_dol);
            } else {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
//            Toast.makeText(context, "请授予应用悬浮窗权限,并设置允许后台运行", Toast.LENGTH_SHORT).show();
        }
    }

    //申请无障碍权限
    public static void requestWxs(Context context){
        if (!isServiceON(context)){
            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
//            Toast.makeText(context, "请授予快启动无障碍权限", Toast.LENGTH_SHORT).show();
        }

    }


    //申请后台运行权限
    public static void requestIgnoreBatteryOptimizations(Context context) {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取悬浮窗权限状态
     *
     * @param context
     * @return 1或其他是没有打开，0是打开，该状态的定义和{@link android.app.AppOpsManager#MODE_ALLOWED}，MODE_IGNORED等值差不多，自行查阅源码
     */
    public static int getFloatPermissionStatus(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("context is null");
        }
        String packageName = context.getPackageName();
        Uri uri = Uri.parse("content://com.iqoo.secure.provider.secureprovider/allowfloatwindowapp");
        String selection = "pkgname = ?";
        String[] selectionArgs = new String[]{packageName};
        Cursor cursor = context
                .getContentResolver()
                .query(uri, null, selection, selectionArgs, null);
        if (cursor != null) {
            cursor.getColumnNames();
            if (cursor.moveToFirst()) {
                int currentmode = cursor.getInt(cursor.getColumnIndex("currentlmode"));
                cursor.close();
                return currentmode;
            } else {
                cursor.close();
                return getFloatPermissionStatus2(context);
            }

        } else {
            return getFloatPermissionStatus2(context);
        }
    }


    /**
     * vivo比较新的系统获取方法
     *
     * @param context
     * @return
     */
    private static int getFloatPermissionStatus2(Context context) {
        String packageName = context.getPackageName();
        Uri uri2 = Uri.parse("content://com.vivo.permissionmanager.provider.permission/float_window_apps");
        String selection = "pkgname = ?";
        String[] selectionArgs = new String[]{packageName};
        Cursor cursor = context
                .getContentResolver()
                .query(uri2, null, selection, selectionArgs, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int currentmode = cursor.getInt(cursor.getColumnIndex("currentmode"));
                cursor.close();
                return currentmode;
            } else {
                cursor.close();
                return 1;
            }
        }
        return 1;
    }

}
